/*
 * Copyright (c) 2023-2024 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.screw.execute;

import java.io.ByteArrayOutputStream;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.builder.BuilderException;
import org.elsfs.cloud.common.util.lang.ExceptionUtils;
import org.elsfs.cloud.screw.Configuration;
import org.elsfs.cloud.screw.engine.EngineFactory;
import org.elsfs.cloud.screw.engine.TemplateEngine;
import org.elsfs.cloud.screw.metadata.model.DataModel;
import org.elsfs.cloud.screw.process.DataModelProcess;

/** 文档生成 */
@Slf4j
public class DocumentationExecute extends AbstractExecute {

  public DocumentationExecute(Configuration config) {
    super(config);
  }

  /**
   * 执行
   *
   * @return ByteArrayOutputStream
   * @throws BuilderException BuilderException
   */
  @Override
  public ByteArrayOutputStream execute(String dsName) throws BuilderException {
    long start = System.currentTimeMillis();

    try {
      // 处理数据
      DataModel dataModel = new DataModelProcess(config).process(dsName);
      // 产生文档
      TemplateEngine produce = new EngineFactory(config.getEngineConfig()).newInstance();
      return produce.produce(dataModel, getDocName(dataModel.getDatabase()));

    } catch (Exception e) {
      throw ExceptionUtils.mpe(e);
    } finally {
      logger.debug(
          "database document generation complete time consuming:{}ms",
          System.currentTimeMillis() - start);
    }
  }
}
